package com.gaoyi.crm.activity;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;

import com.gaoyi.crm.R;
import com.gaoyi.crm.activity.base.BaseActivity;
import com.gaoyi.crm.constant.BundleKeyName;
import com.gaoyi.crm.constant.EventCode;
import com.gaoyi.crm.constant.RequestCode;
import com.gaoyi.crm.databinding.ActivityMainBinding;
import com.gaoyi.crm.db.bean.Event;
import com.gaoyi.crm.fragment.ResultFragment;
import com.gaoyi.crm.fragment.ScanDoneFragment;
import com.gaoyi.crm.fragment.ScannedListFragment;
import com.gaoyi.crm.receiver.NetworkBroadcastReceiver;
import com.gaoyi.crm.util.PermissionUtils;
import com.gaoyi.crm.util.ToastUtil;
import com.gaoyi.crm.util.Utils;
import com.gaoyi.crm.vm.MainViewModel;
import com.gs.zxinglibrary.zxing.activity.CodeUtils;

import java.util.Map;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {

    private ActivityResultLauncher<Intent> mScanResult;
    private NavController mController;
    private NetworkBroadcastReceiver mReceiver;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        mPermissionsResult = registerForPermissionsResult();
        mScanResult = registerForActivityResult(RequestCode.REQUEST_SCAN);
        registerReceiver();
    }

    /**
     * 监听网络变化广播
     */
    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        mReceiver = new NetworkBroadcastReceiver();
        registerReceiver(mReceiver, intentFilter);
    }

    /**
     * 设置底部导航默认不选中
     */
    private void menuUnCheckAllItems(Menu menu) {
        menu.setGroupCheckable(0, true, false);
        for (int i = 0; i < menu.size(); i++) {
            menu.getItem(i).setChecked(false);
        }
        menu.setGroupCheckable(0, true, true);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mController = Navigation.findNavController(this, R.id.fragment);
        mController.addOnDestinationChangedListener((controller, destination, arguments) -> {
            int id = destination.getId();
            if (id == R.id.homePageFragment) {
                menuUnCheckAllItems(mBinding.nav.getMenu());
            } else if (id == R.id.scanDoneFragment) {
                mBinding.nav.getMenu().getItem(1).setChecked(true);
            }
        });
        NavigationUI.setupWithNavController(mBinding.nav, mController);
        mBinding.nav.setOnItemSelectedListener(item -> {
            if (item.getItemId() == R.id.enquiryFragment) {
                enquiry();
            } else {
                NavigationUI.onNavDestinationSelected(item, mController);
            }
            return true;
        });
    }

    private void enquiry() {
        boolean permission = PermissionUtils.addPermission(this, new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        }, mPermissionsResult); // 判断是否有权限
        if (permission) {
            toScan();
        }
    }

    private void toScan() {
        Utils.scan(mContext, mScanResult, 1);
    }

    @Override
    protected void event(Event event) {
        // 点击了ActionBar的HomePage
        if (event.getWhat() == EventCode.EVENT_FRAGMENT) {
            NavDestination navDestination = mController.getCurrentDestination(); // 获取当前的导航
            if (navDestination != null && navDestination.getId() == R.id.homePageFragment) {
                return;
            }
            Utils.backToHomePage(mController);
        }
    }

    @Override
    public void onBackPressed() {
        int fragmentId = getCurrentFragmentId();
        // 按返回键时，当前显示在ResultFragment
        if (fragmentId == R.id.resultFragment) {
            Fragment primaryNavigationFragment = getPrimaryNavigationFragment();
            if (primaryNavigationFragment instanceof ResultFragment) {
                if (((ResultFragment) primaryNavigationFragment).onBackPressed()) {
                    return;
                }
            }
        } else if (fragmentId == R.id.scannedListFragment) { // scannedListFragment返回需要传递参数给newPromotionFragment
            Fragment primaryNavigationFragment = getPrimaryNavigationFragment();
            if (primaryNavigationFragment instanceof ScannedListFragment) {
                ((ScannedListFragment) primaryNavigationFragment).onBackPressed();
            }
        }
        super.onBackPressed();
    }

    private Fragment getPrimaryNavigationFragment() {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);
        return fragment == null ? null : fragment.getChildFragmentManager().getPrimaryNavigationFragment();
    }

    /**
     * 获取当前显示的Fragment Id
     */
    private int getCurrentFragmentId() {
        NavDestination navDestination = mController.getCurrentDestination(); // 获取当前的导航
        return navDestination == null ? 0 : navDestination.getId();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            if (getCurrentFragmentId() == R.id.scanDoneFragment) { // scan next
                return scanNext();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean scanNext() {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);
        if (fragment == null) return false;
        Fragment primaryNavigationFragment = fragment.getChildFragmentManager().getPrimaryNavigationFragment();
        if (primaryNavigationFragment instanceof ScanDoneFragment) {
            ((ScanDoneFragment) primaryNavigationFragment).scanNext();
            return true;
        }
        return false;
    }

    @Override
    protected void onRequestPermissionsResult(Map<String, Boolean> result) {
        if (PermissionUtils.requestPermissionResult(result, Manifest.permission.CAMERA)
                && PermissionUtils.requestPermissionResult(result, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            toScan();
        } else {
            ToastUtil.showToast(R.string.no_permission);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, ActivityResult result) {
        if (requestCode == RequestCode.REQUEST_SCAN) {
            scanResult(result);
        }
    }

    private void scanResult(ActivityResult result) {
        Intent data = result.getData();
        if (result.getResultCode() == 0 || data == null) {
            return;
        }
        Bundle dataExtras = data.getExtras();
        if (dataExtras == null) {
            return;
        }
        if (dataExtras.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
            String itemNo = dataExtras.getString(CodeUtils.RESULT_STRING);
            Bundle bundle = new Bundle();
            bundle.putString(BundleKeyName.RESULT, itemNo);
            mController.navigate(R.id.scanDoneFragment, bundle);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }
}